package settings

import (
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"os"
	"path/filepath"
)

func LoadSSL(sslDir, keyFile, certFile string, secSkip bool) (*tls.Config, error) {
	sslKeyPath := filepath.Join(sslDir, keyFile)
	sslCrtPath := filepath.Join(sslDir, certFile)
	cert, err := tls.LoadX509KeyPair(sslCrtPath, sslKeyPath)
	if err != nil {
		return nil, fmt.Errorf("failed to load SSL certificate, err=%w", err)
	}
	caCert, err := os.ReadFile(sslCrtPath)
	if err != nil {
		return nil, fmt.Errorf("failed to read CA certificate, err=%v", err)
	}
	certPool := x509.NewCertPool()
	if !certPool.AppendCertsFromPEM(caCert) {
		return nil, fmt.Errorf("failed to append CA certificates")
	}
	tlsConf := &tls.Config{
		Certificates:       []tls.Certificate{cert},
		ClientAuth:         tls.NoClientCert,
		InsecureSkipVerify: true,
		RootCAs:            certPool,
	}
	if !secSkip {
		tlsConf.InsecureSkipVerify = false
		tlsConf.ClientAuth = tls.RequireAndVerifyClientCert
	}
	return tlsConf, nil
}
